<?php


namespace app\home\controller;

use app\home\model\Index as IndexModel;

use app\home\model\User;
use app\home\model\User as UserModel;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;


class Index extends Controller
{

    public function index()
    {
        $indexModel = new IndexModel();
        $result = $indexModel->index();
        if ($result) {
            return view('home@index/index', [
                'category' => $result
            ]);
        } else {
            alert('查询失败');
        }
    }

    public function loadIndex()
    {
        $indexModel = new IndexModel();
        $result = $indexModel->index();
        if (Session::get('name')) {
            return view('home@index/index2',['category' => $result]);
        }else{
            return $this->error('请登录', '/');
        }
    }

    public function reguser()
    {

        $arr = input('post.');

        $result = Db::table('hb_user')->where('nickname', $arr['nickname'])
            ->whereOr('tel', $arr['tel'])
            ->whereOr('email', $arr['email'])
            ->select();

        if ($result) {
            return $this->error('手机号或邮箱或账号已存在,请重试!');
        }

        $arr['regtime'] = time();
        $arr['status'] = 1;

        $user = new UserModel();
        $row = $user->adduser($arr);

        if ($row) {
            $this->success('注册成功!', '/Users/loginjump');
        } else {
            return $this->error('注册失败,请重试!');
        }

    }

    public function logindo()
    {

        //如果是ajax请求区间
        if (Request::instance()->isAjax()) {
            parse_str(input('post.mes'), $arr);
            $user = new UserModel();
            $row = $user->checkLogin($arr);
            //用户存在情况下
            if ($row) {
                Session::set('name', [
                    'name' => $row['nickname'],
                    'id' => $row['id'],
                ]);
                return ['登陆成功!', '你好' . $row['nickname']];
            } else {
                echo '账号或密码有误!';
            }
        }else{
            //不是区间
            $arr = input('post.');
            $user = new UserModel();
            $row = $user->checkLogin($arr);
            //用户存在情况下
            if ($row) {
                Session::set('name', [
                    'name' => $row['nickname'],
                    'id' => $row['id'],
                ]);
                return $this->success('登录成功 (*^▽^*)!','/');
            } else {
               return $this->error('登陆失败o(╥﹏╥)o,请重试!');
            }
        }
    }

    public function loginout()
    {
        Session::clear();
        return $this->success('退出成功~', '/');
    }

    public function loginjump()
    {
        return view('home@index/login');
    }

}
